package com.qf.application.controller;

import com.qf.application.commons.exception.BusinessException;
import com.qf.application.commons.utils.JWTUtils;
import com.qf.application.commons.utils.R;
import com.qf.application.context.UserContextHolder;
import com.qf.application.entity.LoginUser;
import com.qf.application.entity.User;
import com.qf.application.entity.UserToken;
import com.qf.application.service.IUserService;
import com.qf.application.service.impl.LoginServiceImpl;
import com.qf.application.service.impl.UserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    private LoginServiceImpl loginService;

    @Autowired
    private UserTokenService tokenService;


    // 返回当前登录的用户？？--》如何获取当前登录用户 -->拿到token进行解析？
    @GetMapping("/userInfo")
    public R userInfo() {
        LoginUser userToken = UserContextHolder.get();
        return R.ok().put("data", userToken);
    }


    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> param) {
        // 1.认证
        User user = loginService.login(param);

        // 2.认证成功了需要创建一个UserToken对象
        String jwtToken = tokenService.createToken(user);

        return R.ok().put("token", jwtToken);
    }
}
